<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">

  <script>
    (function(){
        if(''){
            if (prompt('请输入文章密码') !== ''){
                alert('密码错误！');
                history.back();
            }
        }
    })();
  </script>









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon.ico?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.ico?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.ico?v=5.1.3">


  <link rel="mask-icon" href="/images/favicon.ico?v=5.1.3" color="#222">





  <meta name="keywords" content="Ansible,极简教程系列," />










<meta name="description" content="Ansible 极简教程一、基本部署简介ansible是一个自动化管理工具，它足够简单且足够强大来管理大批量设备。可用于配置系统，部署软件以及组合复杂任务。 特性 无agent模式，push模式，这一点与fabric有几分类似 并发执行 可用任何语言写扩展模块 有类似Puppet（RAL）或者SaltStack（state）的playbook 灵活的匹配规则，通配符，正则  安装Ansible12">
<meta name="keywords" content="Ansible,极简教程系列">
<meta property="og:type" content="article">
<meta property="og:title" content="Ansible极简教程">
<meta property="og:url" content="http://www.kangvcar.com/Ansible极简教程/index.html">
<meta property="og:site_name" content="Kangvcar | Blogs">
<meta property="og:description" content="Ansible 极简教程一、基本部署简介ansible是一个自动化管理工具，它足够简单且足够强大来管理大批量设备。可用于配置系统，部署软件以及组合复杂任务。 特性 无agent模式，push模式，这一点与fabric有几分类似 并发执行 可用任何语言写扩展模块 有类似Puppet（RAL）或者SaltStack（state）的playbook 灵活的匹配规则，通配符，正则  安装Ansible12">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-06-18T08:41:44.739Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Ansible极简教程">
<meta name="twitter:description" content="Ansible 极简教程一、基本部署简介ansible是一个自动化管理工具，它足够简单且足够强大来管理大批量设备。可用于配置系统，部署软件以及组合复杂任务。 特性 无agent模式，push模式，这一点与fabric有几分类似 并发执行 可用任何语言写扩展模块 有类似Puppet（RAL）或者SaltStack（state）的playbook 灵活的匹配规则，通配符，正则  安装Ansible12">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.3',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://www.kangvcar.com/Ansible极简教程/"/>



  <script>
  (function(i,s,o,g,r,a,m){i["DaoVoiceObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;a.charset="utf-8";m.parentNode.insertBefore(a,m)})(window,document,"script",('https:' == document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/0f81ff2f.js","daovoice")
  daovoice('init', {
      app_id: "f8921861"
    });
  daovoice('update');
  </script>





  <title>Ansible极简教程 | Kangvcar | Blogs</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
      <a href="https://github.com/kangvcar/kangvcar.github.io" class="github-corner" aria-label="View source on Github"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#FD6C6C; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
<!--       <a href="https://github.com/kangvcar/kangvcar.github.io"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/365986a132ccd6a44c23a9169022c0b5c890c387/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f7265645f6161303030302e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png"></a>
 -->
    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Kangvcar | Blogs</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">知识的广度是深度的副产品</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://www.kangvcar.com/Ansible极简教程/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Kangvcar">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/uploads/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Kangvcar | Blogs">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Ansible极简教程</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-06-14T20:47:44+08:00">
                2018-06-14
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Ansible/" itemprop="url" rel="index">
                    <span itemprop="name">Ansible</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/Ansible极简教程/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count"
                        data-disqus-identifier="Ansible极简教程/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  5,418
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  25
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="Ansible-极简教程"><a href="#Ansible-极简教程" class="headerlink" title="Ansible 极简教程"></a>Ansible 极简教程</h1><h2 id="一、基本部署"><a href="#一、基本部署" class="headerlink" title="一、基本部署"></a>一、基本部署</h2><h3 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h3><p>ansible是一个自动化管理工具，它足够简单且足够强大来管理大批量设备。可用于配置系统，部署软件以及组合复杂任务。</p>
<h3 id="特性"><a href="#特性" class="headerlink" title="特性"></a>特性</h3><ul>
<li>无agent模式，push模式，这一点与fabric有几分类似</li>
<li>并发执行</li>
<li>可用任何语言写扩展模块</li>
<li>有类似Puppet（RAL）或者SaltStack（state）的playbook</li>
<li>灵活的匹配规则，通配符，正则</li>
</ul>
<h3 id="安装Ansible"><a href="#安装Ansible" class="headerlink" title="安装Ansible"></a>安装Ansible</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#</span><span class="bash"> yum -y install epel-release</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> yum list all *ansible*</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> yum info ansible</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> yum -y install ansible</span></span><br></pre></td></tr></table></figure>
<h3 id="Ansible配置文件"><a href="#Ansible配置文件" class="headerlink" title="Ansible配置文件"></a>Ansible配置文件</h3><figure class="highlight dts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta-keyword">/etc/</span>ansible/ansible.cfg    主配置文件</span><br><span class="line"><span class="meta-keyword">/etc/</span>ansible/hosts          Inventory</span><br></pre></td></tr></table></figure>
<h3 id="使用秘钥方式连接"><a href="#使用秘钥方式连接" class="headerlink" title="使用秘钥方式连接"></a>使用秘钥方式连接</h3><figure class="highlight lsl"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"># ssh-keygen -t rsa </span><br><span class="line"># ssh-copy-id -i /root/.ssh/id_rsa.pub root@<span class="number">192.168</span><span class="number">.10</span><span class="number">.149</span></span><br><span class="line"># ssh-copy-id -i /root/.ssh/id_rsa.pub root@<span class="number">192.168</span><span class="number">.10</span><span class="number">.113</span></span><br><span class="line"># ssh-copy-id -i /root/.ssh/id_rsa.pub root@<span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span></span><br></pre></td></tr></table></figure>
<h3 id="使用帮助"><a href="#使用帮助" class="headerlink" title="使用帮助"></a>使用帮助</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#</span><span class="bash"> ansible-doc -l                列出ansible所有的模块</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> ansible-doc -s MODULE_NAME    查看指定模块具体适用</span></span><br></pre></td></tr></table></figure>
<h3 id="Ansible命令应用基础"><a href="#Ansible命令应用基础" class="headerlink" title="Ansible命令应用基础"></a>Ansible命令应用基础</h3><figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">语法：ansible &lt;host-pattern&gt; [-f forks] [-m module_name] [-a args]</span><br><span class="line"></span><br><span class="line">&lt;host-pattern&gt;  这次命令对哪些主机生效的</span><br><span class="line">    inventory<span class="built_in"> group </span>name</span><br><span class="line">    ip</span><br><span class="line">    all</span><br><span class="line">-f forks        一次处理多少个主机</span><br><span class="line">-m module_name  要使用的模块</span><br><span class="line">-a args         模块特有的参数</span><br><span class="line"></span><br><span class="line"><span class="comment"># ansible 192.168.10.113 -m command -a 'date'</span></span><br><span class="line"><span class="comment"># ansible webserver -m command -a 'date'</span></span><br><span class="line"><span class="comment"># ansible all -m command -a 'date'</span></span><br></pre></td></tr></table></figure>
<h2 id="二、常见模块"><a href="#二、常见模块" class="headerlink" title="二、常见模块"></a>二、常见模块</h2><h3 id="command"><a href="#command" class="headerlink" title="command"></a>command</h3><figure class="highlight livecodeserver"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">command</span>     命令模块(默认模块)用于在远程主机执行命令；不能使用变量，管道等</span><br><span class="line">    <span class="comment"># ansible all -a 'date'</span></span><br></pre></td></tr></table></figure>
<h3 id="cron"><a href="#cron" class="headerlink" title="cron"></a>cron</h3><figure class="highlight excel"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">cron        计划任务    </span><br><span class="line">    <span class="built_in">month</span>   指定月份</span><br><span class="line">    <span class="built_in">minute</span>  指定分钟</span><br><span class="line">    job     指定任务</span><br><span class="line">    <span class="built_in">day</span>     表示那一天</span><br><span class="line">    <span class="built_in">hour</span>    指定小时</span><br><span class="line">    <span class="built_in">weekday</span> 表示周几</span><br><span class="line">    state   表示是添加还是删除</span><br><span class="line">        present：安装</span><br><span class="line">        absent：移除</span><br><span class="line">    # ansible webserver -m cron -a '<span class="built_in">minute</span>=<span class="string">"*/10"</span> job=<span class="string">"/bin/echo hello"</span> name=<span class="string">"test cron job"</span>'   #不写默认都是*，每个任务都必须有一个名字 </span><br><span class="line">    # ansible webserver -a 'crontab -l'</span><br><span class="line">    # ansible webserver -m cron -a '<span class="built_in">minute</span>=<span class="string">"*/10"</span> job=<span class="string">"/bin/echo hello"</span> name=<span class="string">"test cron job"</span> state=absent'  #移除任务</span><br></pre></td></tr></table></figure>
<h3 id="user"><a href="#user" class="headerlink" title="user"></a>user</h3><figure class="highlight pf"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">user</span>    用户账号管理</span><br><span class="line">    name    用户名</span><br><span class="line">    uid     uid</span><br><span class="line">    <span class="keyword">state</span>   状态  </span><br><span class="line">    <span class="keyword">group</span>   属于哪个组</span><br><span class="line">    groups  附加组</span><br><span class="line">    home    家目录</span><br><span class="line">    createhome  是否创建家目录</span><br><span class="line">    comment 注释信息</span><br><span class="line">    system  是否是系统用户</span><br><span class="line">    </span><br><span class="line">    <span class="comment"># ansible all -m user -a 'name="user1"'</span></span><br><span class="line">    <span class="comment"># ansible all -m user -a 'name="user1" state=absent'</span></span><br></pre></td></tr></table></figure>
<h3 id="group"><a href="#group" class="headerlink" title="group"></a>group</h3><figure class="highlight clean"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">group   组管理</span><br><span class="line">    gid     gid      </span><br><span class="line">    name    组名               </span><br><span class="line">    state   状态           </span><br><span class="line">    <span class="keyword">system</span>  是否是系统组</span><br><span class="line">    # ansible webserver -m group -a <span class="string">'name=mysql gid=306 system=yes'</span></span><br><span class="line">    # ansible webserver -m user -a <span class="string">'name=mysql uid=306 system=yes group=mysql'</span></span><br><span class="line">``` </span><br><span class="line"></span><br><span class="line">### copy</span><br><span class="line">``` </span><br><span class="line">copy    复制文件(复制本地文件到远程主机的指定位置)</span><br><span class="line">    src     定义本地源文件路径</span><br><span class="line">    dest    定义远程目录文件路径(绝对路径)</span><br><span class="line">    owner   属主</span><br><span class="line">    group   属组</span><br><span class="line">    mode    权限</span><br><span class="line">    content 取代src=,表示直接用此处的信息生成为文件内容</span><br><span class="line">    # yum -y install libselinux-python</span><br><span class="line">    # ansible all -m copy -a <span class="string">'src=/etc/fstab dest=/tmp/fstab.ansible owner=root mode=640'</span></span><br><span class="line">    # ansible all -m copy -a <span class="string">'content="hello ansible\nHi ansible" dest=/tmp/test.ansible'</span></span><br></pre></td></tr></table></figure>
<h3 id="file"><a href="#file" class="headerlink" title="file"></a>file</h3><figure class="highlight vhdl"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">file</span>    设置文件的属性</span><br><span class="line">    path|dest|name  对那个文件做设定</span><br><span class="line">    </span><br><span class="line">    创建文件的符号链接：</span><br><span class="line">        src：    指定源文件</span><br><span class="line">        path：   指明符号链接文件路径</span><br><span class="line">    # ansible <span class="keyword">all</span> -m <span class="keyword">file</span> -a <span class="symbol">'owner</span>=mysql <span class="keyword">group</span>=mysql mode=<span class="number">644</span> path=/tmp/fstab.ansible'</span><br><span class="line">    # ansible <span class="keyword">all</span> -m <span class="keyword">file</span> -a <span class="symbol">'path</span>=/tmp/fstab.link src=/tmp/fstab.ansible state=link'</span><br></pre></td></tr></table></figure>
<h3 id="ping"><a href="#ping" class="headerlink" title="ping"></a>ping</h3><figure class="highlight autoit"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">ping</span>    测试指定主机是否能连接</span><br><span class="line">    <span class="meta"># ansible all -m ping</span></span><br></pre></td></tr></table></figure>
<h3 id="service"><a href="#service" class="headerlink" title="service"></a>service</h3><figure class="highlight pf"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">service 管理服务运行状态</span><br><span class="line">    enabled 是否开机自动启动</span><br><span class="line">    name    指定服务名</span><br><span class="line">    <span class="keyword">state</span>   指定服务状态</span><br><span class="line">        started     启动服务</span><br><span class="line">        stoped      停止服务</span><br><span class="line">        restarted   重启服务</span><br><span class="line">    arguments   服务的参数</span><br><span class="line">    <span class="comment"># ansible webserver -m service -a 'enabled=true name=httpd state=started'</span></span><br></pre></td></tr></table></figure>
<h3 id="shell"><a href="#shell" class="headerlink" title="shell"></a>shell</h3><figure class="highlight dockerfile"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">shell</span><span class="bash">   在远程主机上运行命令</span></span><br><span class="line"><span class="bash">    尤其是用到管道变量等功能的复杂命令</span></span><br><span class="line"><span class="bash">    <span class="comment"># ansible all -m shell -a 'echo magedu | passwd --stdin user1'</span></span></span><br></pre></td></tr></table></figure>
<h3 id="script"><a href="#script" class="headerlink" title="script"></a>script</h3><figure class="highlight applescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">script</span>  将本地脚本复制到远程主机并运行之</span><br><span class="line">    <span class="comment"># ansible all -m script -a '/tmp/test.sh'</span></span><br></pre></td></tr></table></figure>
<h3 id="yum"><a href="#yum" class="headerlink" title="yum"></a>yum</h3><figure class="highlight pf"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">yum     安装程序包</span><br><span class="line">    name    程序包名称(不指定版本就安装最新的版本latest)</span><br><span class="line">    <span class="keyword">state</span>   present,latest表示安装，absent表示卸载</span><br><span class="line">    <span class="comment"># ansible webserver -m yum -a 'name=httpd'</span></span><br><span class="line">    <span class="comment"># ansible all -m yum -a 'name=ntpdate'  #默认就是安装</span></span><br><span class="line">    <span class="comment"># ansible all -m yum -a 'name=ntpdate state=absent'</span></span><br></pre></td></tr></table></figure>
<h3 id="setup"><a href="#setup" class="headerlink" title="setup"></a>setup</h3><figure class="highlight arduino"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">setup</span>   收集远程主机的facts</span><br><span class="line">    每个被管理节点在接受并运行管理命令之前，会将自己主机相关信息，如操作系统版本，IP地址等报告给远程的ansible主机 </span><br><span class="line">    <span class="meta"># ansible all -m setup</span></span><br></pre></td></tr></table></figure>
<h2 id="三、Ansible-playbook"><a href="#三、Ansible-playbook" class="headerlink" title="三、Ansible playbook"></a>三、Ansible playbook</h2><p>组成结构：<br><figure class="highlight livecodeserver"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">inventory       <span class="comment">#以下操作应用的主机</span></span><br><span class="line">modules         <span class="comment">#调用哪些模块做什么样的操作</span></span><br><span class="line">ad hoc commands <span class="comment">#在这些主机上运行哪些命令</span></span><br><span class="line">playbooks   </span><br><span class="line">    tasks       <span class="comment">#任务,即调用模块完成的某操作</span></span><br><span class="line">    <span class="built_in">variable</span>    <span class="comment">#变量</span></span><br><span class="line">    templates   <span class="comment">#模板</span></span><br><span class="line">    handlers    <span class="comment">#处理器，由某事件触发执行的操作</span></span><br><span class="line">    roles       <span class="comment">#角色</span></span><br></pre></td></tr></table></figure></p>
<h2 id="四、YAML"><a href="#四、YAML" class="headerlink" title="四、YAML"></a>四、YAML</h2><h3 id="4-1-YAML介绍"><a href="#4-1-YAML介绍" class="headerlink" title="4.1 YAML介绍"></a>4.1 YAML介绍</h3><p>YAML是一个可读性高的用来表达资料序列的格式。YAML参考了其它多种语言，包括：XML、C语言、Python、Perl以及电子邮件格式RFC2822等。ClarkEvans在2001年首次发表了这种语言，另外Ingy dot Net与Oren Ben-Kiki也是这语言的共同设计者。</p>
<p>playbook是用yaml语法编写的，但你只需要了解如下几条简单的规则即可：</p>
<ul>
<li>文档以<code>---</code>开头</li>
<li><code>-</code>代表列表，也可以写成`[a, b]``</li>
<li><code>:</code>代表字典，也可以写成`{a: b}``</li>
<li>如果字符冲突用双引号把对应字符串引起来</li>
</ul>
<blockquote>
<p>更多的内容及规范参见<a href="http://www.yaml.org" target="_blank" rel="external">http://www.yaml.org</a></p>
</blockquote>
<h3 id="4-2-YAML语法"><a href="#4-2-YAML语法" class="headerlink" title="4.2 YAML语法"></a>4.2 YAML语法</h3><p>YAML的语法和其他高阶语言类似，并且可以简单表达清单、散列表、标量等数据结构，其结构(structure)通过空格来展示，序列(sequence)里的项用”-“来表示，Map里面的键值对用”:”分割，下面是一个示例。<br><figure class="highlight less"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">name</span>: john smith</span><br><span class="line"><span class="attribute">age</span>: <span class="number">41</span></span><br><span class="line"><span class="attribute">gender</span>: male</span><br><span class="line"><span class="attribute">spouse</span>:</span><br><span class="line">    <span class="attribute">name</span>:jane smith</span><br><span class="line">    <span class="attribute">age</span>:<span class="number">37</span></span><br><span class="line">    <span class="attribute">gender</span>: female</span><br><span class="line"><span class="attribute">children</span>:</span><br><span class="line">    -   <span class="attribute">name</span>:jimmy smith</span><br><span class="line">        <span class="attribute">age</span>:<span class="number">17</span></span><br><span class="line">        <span class="attribute">gender</span>: male</span><br><span class="line">    -   <span class="attribute">name</span>:jenny smith</span><br><span class="line">        <span class="attribute">age</span>: <span class="number">13</span></span><br><span class="line">        <span class="attribute">gender</span>: female</span><br></pre></td></tr></table></figure></p>
<p>YAML文件扩展名通常为.yaml，如example.yaml</p>
<h2 id="五、Ansible基础元素"><a href="#五、Ansible基础元素" class="headerlink" title="五、Ansible基础元素"></a>五、Ansible基础元素</h2><h3 id="5-1-变量"><a href="#5-1-变量" class="headerlink" title="5.1 变量"></a>5.1 变量</h3><h4 id="5-1-1-变量命名"><a href="#5-1-1-变量命名" class="headerlink" title="5.1.1 变量命名"></a>5.1.1 变量命名</h4><p>变量名仅能由字母、数字和下划线组成，且只能以字母开头。</p>
<h4 id="5-1-2-facts"><a href="#5-1-2-facts" class="headerlink" title="5.1.2 facts"></a>5.1.2 facts</h4><p>facts是由正在通信的远程目标主机发回的信息，这些信息被保存在ansible变量中。要获取指定的远程主机所支持的所有facts，可使用如下命令进行：<br><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#</span><span class="bash">ansible hostname -m setup</span></span><br></pre></td></tr></table></figure></p>
<h4 id="5-1-3-register"><a href="#5-1-3-register" class="headerlink" title="5.1.3 register"></a>5.1.3 register</h4><p>把任务的输出定义为变量，然后用于其他任务，实例如下：<br><figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">tasks:</span></span><br><span class="line"><span class="attr">    - shell:</span> <span class="string">/usr/bin/foo</span></span><br><span class="line"><span class="attr">      register:</span> <span class="string">foo_result</span></span><br><span class="line"><span class="attr">      ignore_errors:</span> <span class="literal">True</span></span><br></pre></td></tr></table></figure></p>
<h4 id="5-1-4-通过命令行传递变量"><a href="#5-1-4-通过命令行传递变量" class="headerlink" title="5.1.4 通过命令行传递变量"></a>5.1.4 通过命令行传递变量</h4><p>在运行playbook的时候也可以传递一些变量供playbook使用，示例如下：<br><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-id">#ansible-playbook</span> test<span class="selector-class">.yml</span> --extra-vars <span class="string">"hosts=www user=mageedu"</span></span><br></pre></td></tr></table></figure></p>
<h4 id="5-1-5-通过roles传递变量"><a href="#5-1-5-通过roles传递变量" class="headerlink" title="5.1.5 通过roles传递变量"></a>5.1.5 通过roles传递变量</h4><p>当给一个主机应用角色的时候可以传递变量，然后在角色内使用这些变量，示例如下：<br><figure class="highlight haml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">-<span class="ruby"> <span class="symbol">hosts:</span> webserver</span></span><br><span class="line"><span class="ruby">  <span class="symbol">roles:</span></span></span><br><span class="line"><span class="ruby">    - common</span></span><br><span class="line"><span class="ruby">    - &#123;<span class="symbol">role:</span> foo_app_instance, <span class="symbol">dir:</span> <span class="string">'/web/htdocs/a.com'</span>, <span class="symbol">port:</span> <span class="number">8080</span>&#125;</span></span><br></pre></td></tr></table></figure></p>
<h3 id="5-2-Inventory"><a href="#5-2-Inventory" class="headerlink" title="5.2 Inventory"></a>5.2 Inventory</h3><p>ansible的主要功用在于批量主机操作，为了便捷的使用其中的部分主机，可以在inventory file中将其分组命名，默认的inventory file为<code>/etc/ansible/hosts</code></p>
<p>inventory file可以有多个，且也可以通过Dynamic Inventory来动态生成。</p>
<h4 id="5-2-1-inventory文件格式"><a href="#5-2-1-inventory文件格式" class="headerlink" title="5.2.1 inventory文件格式"></a>5.2.1 inventory文件格式</h4><p>inventory文件遵循INI文件风格，中括号中的字符为组名。可以将同一个主机同时归并到多个不同的组中；此外，当如若目标主机使用非默认的SSH端口，还可以在主机名称之后使用冒号加端口号来表明。<br><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">ntp<span class="selector-class">.kangvcar</span><span class="selector-class">.com</span></span><br><span class="line"></span><br><span class="line">[webserver]</span><br><span class="line">www1<span class="selector-class">.kangvcar</span><span class="selector-class">.com</span>:<span class="number">2222</span></span><br><span class="line">www2<span class="selector-class">.kangvcar</span><span class="selector-class">.com</span></span><br><span class="line"></span><br><span class="line">[dbserver]</span><br><span class="line">db1<span class="selector-class">.kangvcar</span><span class="selector-class">.com</span></span><br><span class="line">db2<span class="selector-class">.kangvcar</span><span class="selector-class">.com</span></span><br><span class="line">db3<span class="selector-class">.kangvcar</span><span class="selector-class">.com</span></span><br><span class="line"></span><br><span class="line">如果主机名遵循相似的命名模式，还可使用列表的方式标识个主机，例如：</span><br><span class="line">[webserver]</span><br><span class="line">www[<span class="number">01</span>:<span class="number">50</span>]<span class="selector-class">.example</span><span class="selector-class">.com</span></span><br><span class="line"></span><br><span class="line">[databases]</span><br><span class="line">db-[<span class="selector-tag">a</span>:f]<span class="selector-class">.example</span><span class="selector-class">.com</span></span><br></pre></td></tr></table></figure></p>
<h4 id="5-2-2-主机变量"><a href="#5-2-2-主机变量" class="headerlink" title="5.2.2 主机变量"></a>5.2.2 主机变量</h4><p>可以在inventory中定义主机时为其添加主机变量以便于在playbook中使用，例如：<br><figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">[webserver]</span><br><span class="line">www1.kangvcar.com <span class="attribute">http_port</span>=80 <span class="attribute">maxRequestsPerChild</span>=808</span><br><span class="line">www2.kangvcar.com <span class="attribute">http_port</span>=8080 <span class="attribute">maxRequestsPerChild</span>=909</span><br></pre></td></tr></table></figure></p>
<h4 id="5-2-3-组变量"><a href="#5-2-3-组变量" class="headerlink" title="5.2.3 组变量"></a>5.2.3 组变量</h4><p>组变量是指赋予给指定组内所有主机上的在playbook中可用的变量。例如：<br><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">[webserver]</span><br><span class="line">www1<span class="selector-class">.kangvcar</span><span class="selector-class">.com</span></span><br><span class="line">www2<span class="selector-class">.kangvcar</span><span class="selector-class">.com</span></span><br><span class="line"></span><br><span class="line">[webserver:vars]</span><br><span class="line">ntp_server=ntp<span class="selector-class">.kangvcar</span><span class="selector-class">.com</span></span><br><span class="line">nfs_server=nfs<span class="selector-class">.kangvcar</span><span class="selector-class">.com</span></span><br></pre></td></tr></table></figure></p>
<h4 id="5-2-4-组嵌套"><a href="#5-2-4-组嵌套" class="headerlink" title="5.2.4 组嵌套"></a>5.2.4 组嵌套</h4><p>inventory中，组还可以包含其它的组，并且也可以向组中的主机指定变量。不过，这些变量只能在ansible-playbook中使用，而ansible不支持。例如：<br><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">[apache]</span><br><span class="line">httpd1<span class="selector-class">.kangvcar</span><span class="selector-class">.com</span></span><br><span class="line">httpd2<span class="selector-class">.kangvcar</span><span class="selector-class">.com</span></span><br><span class="line"></span><br><span class="line">[nginx]</span><br><span class="line">ngx1<span class="selector-class">.kangvcar</span><span class="selector-class">.com</span></span><br><span class="line">ngx2<span class="selector-class">.kangvcar</span><span class="selector-class">.com</span></span><br><span class="line"></span><br><span class="line">[webserver:children]    #固定格式</span><br><span class="line">apache</span><br><span class="line">nginx</span><br><span class="line"></span><br><span class="line">[webserver:vars]</span><br><span class="line">ntp_server=ntp<span class="selector-class">.kangvcar</span><span class="selector-class">.com</span></span><br></pre></td></tr></table></figure></p>
<h4 id="5-2-5-inventory参数"><a href="#5-2-5-inventory参数" class="headerlink" title="5.2.5 inventory参数"></a>5.2.5 inventory参数</h4><p>ansible基于ssh连接inventory中指定的远程主机时，还可以通过参数指定其交互方式，这些参数如下所示：<br><figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">ansible_ssh_host</span><br><span class="line">ansible_ssh_port</span><br><span class="line">ansible_ssh_user</span><br><span class="line">ansible_ssh_pass</span><br><span class="line">ansible_sudo_pass</span><br><span class="line">ansible_connection</span><br><span class="line">ansible_ssh_private_key_file</span><br><span class="line">ansible_shell_type</span><br><span class="line">ansible_python_interpreter</span><br></pre></td></tr></table></figure></p>
<h3 id="5-3-条件测试"><a href="#5-3-条件测试" class="headerlink" title="5.3 条件测试"></a>5.3 条件测试</h3><p>如果需要根据变量、facts或此前任务的执行结果来做为某task执行与否的前提时要用到条件测试。</p>
<h4 id="5-3-1-when语句"><a href="#5-3-1-when语句" class="headerlink" title="5.3.1 when语句"></a>5.3.1 when语句</h4><p>在task后添加when字句即可使用条件测试；when语句支持jinja2表达式语句，例如：<br><figure class="highlight vbnet"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">tasks:</span><br><span class="line">  - name: <span class="comment">'shutdown debian flavored system"</span></span><br><span class="line">    command: /sbin/shutdown -h now</span><br><span class="line">    <span class="keyword">when</span>: ansible_os_family == <span class="string">"Debian"</span></span><br></pre></td></tr></table></figure></p>
<p>when语句中还可以使用jinja2的大多”filter”,例如果忽略此前某语句的错误并基于其结果(failed或success)运行后面指定的语句，可使用类似如下形式；<br><figure class="highlight livecodeserver"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">tasks:</span><br><span class="line">  - <span class="keyword">command</span>:/<span class="title">bin</span>/<span class="title">false</span></span><br><span class="line">    register: <span class="built_in">result</span></span><br><span class="line">    ignore_errors: True</span><br><span class="line">  - <span class="keyword">command</span>: /<span class="title">bin</span>/<span class="title">something</span></span><br><span class="line">    when: <span class="built_in">result</span>|failed</span><br><span class="line">  - <span class="keyword">command</span>: /<span class="title">bin</span>/<span class="title">something_else</span></span><br><span class="line">    when: <span class="built_in">result</span>|success</span><br><span class="line">  - <span class="keyword">command</span>: /<span class="title">bin</span>/<span class="title">still</span>/<span class="title">something_else</span></span><br><span class="line">    when: <span class="built_in">result</span>|skipped</span><br></pre></td></tr></table></figure></p>
<p>此外，when语句中还可以使用facts或playbook中定义的变量<br><figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># cat cond.yml </span></span><br><span class="line">- hosts: all</span><br><span class="line">  remote_user: root</span><br><span class="line">  vars:</span><br><span class="line">  - username: user10</span><br><span class="line">  tasks:</span><br><span class="line">  - name: create &#123;&#123; username &#125;&#125; user</span><br><span class="line">    user: name=&#123;&#123; username &#125;&#125; </span><br><span class="line">    when: ansible_fqdn == <span class="string">"node1.exercise.com"</span></span><br></pre></td></tr></table></figure></p>
<h3 id="5-4-迭代"><a href="#5-4-迭代" class="headerlink" title="5.4 迭代"></a>5.4 迭代</h3><p>当有需要重复性执行的任务时，可以使用迭代机制。其使用格式为将需要迭代的内容定义为item变量引用，并通过with_items语句来指明迭代的元素列表即可。例如：<br><figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">- name: <span class="builtin-name">add</span><span class="built_in"> server </span>user</span><br><span class="line">  user: name=&#123;&#123; item &#125;&#125; <span class="attribute">state</span>=persent <span class="attribute">groups</span>=wheel</span><br><span class="line">  with_items:</span><br><span class="line">    - testuser1</span><br><span class="line">    - testuser2</span><br></pre></td></tr></table></figure></p>
<p>上面语句的功能等同于下面的语句：<br><figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">- name: <span class="builtin-name">add</span><span class="built_in"> user </span>testuser1</span><br><span class="line">  user: <span class="attribute">name</span>=testuser1 <span class="attribute">state</span>=present <span class="attribute">group</span>=wheel</span><br><span class="line">- name: <span class="builtin-name">add</span><span class="built_in"> user </span>testuser2</span><br><span class="line">  user: <span class="attribute">name</span>=testuser2 <span class="attribute">state</span>=present <span class="attribute">group</span>=wheel</span><br></pre></td></tr></table></figure></p>
<p>事实上，with_items中可以使用元素还可为hashes，例如：<br><figure class="highlight xquery"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">- name: add several users</span><br><span class="line">  user: name=&#123;&#123; item.name&#125;&#125; state=present groups=&#123;&#123; item.groups &#125;&#125;</span><br><span class="line">  with_items:</span><br><span class="line">    - &#123; name: <span class="string">'testuser1'</span>, groups: <span class="string">'wheel'</span>&#125;</span><br><span class="line">    - &#123; name: <span class="string">'testuser2'</span>, groups: <span class="string">'root'</span>&#125;</span><br></pre></td></tr></table></figure></p>
<p>可以通过with_sequence来生成一个数字序列，其参数包括：</p>
<ul>
<li>start起始数字</li>
<li>end结束数字</li>
<li>stride步长</li>
<li>count个数</li>
<li>format输出的字符串<figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">---</span><br><span class="line">- hosts: all</span><br><span class="line">  tasks:</span><br><span class="line">    # create groups</span><br><span class="line">    - group: <span class="attribute">name</span>=evens <span class="attribute">state</span>=present</span><br><span class="line">    - group: <span class="attribute">name</span>=odds <span class="attribute">state</span>=present</span><br><span class="line">    # create some test users</span><br><span class="line">    - user: name=&#123;&#123; item &#125;&#125; <span class="attribute">state</span>=present <span class="attribute">groups</span>=evens</span><br><span class="line">      with_sequence: <span class="attribute">start</span>=0 <span class="attribute">end</span>=32 <span class="attribute">format</span>=testuser%02x</span><br><span class="line">    # create a series of directories with even numbers <span class="keyword">for</span> some reason</span><br><span class="line">    - file: <span class="attribute">dest</span>=/var/stuff/&#123;&#123; item &#125;&#125; <span class="attribute">state</span>=directory</span><br><span class="line">      with_sequence: <span class="attribute">start</span>=4 <span class="attribute">end</span>=16 <span class="attribute">stride</span>=2</span><br><span class="line">    # a simpler way <span class="keyword">to</span> use the sequence plugin</span><br><span class="line">    # create 4 groups</span><br><span class="line">    - group: <span class="attribute">name</span>=group&#123;&#123; item &#125;&#125; <span class="attribute">state</span>=present</span><br><span class="line">      with_sequence: <span class="attribute">count</span>=4</span><br></pre></td></tr></table></figure>
</li>
</ul>
<blockquote>
<p>Ansible的循环机制还有更多的高级功能，具体请参考官方文档<a href="http://docs.ansible.com/playbooks_loops.html" target="_blank" rel="external">http://docs.ansible.com/playbooks_loops.html</a></p>
</blockquote>
<h2 id="六、模板示例："><a href="#六、模板示例：" class="headerlink" title="六、模板示例："></a>六、模板示例：</h2><figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># grep '&#123;&#123;' conf/httpd.conf </span></span><br><span class="line">MaxClients       &#123;&#123; maxClients &#125;&#125;</span><br><span class="line">Listen &#123;&#123; httpd_port &#125;&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment"># cat /etc/ansible/hosts</span></span><br><span class="line">[webserver]</span><br><span class="line">127.0.0.1 <span class="attribute">httpd_port</span>=80 <span class="attribute">maxClients</span>=100</span><br><span class="line">192.168.10.149 <span class="attribute">httpd_port</span>=8080 <span class="attribute">maxClients</span>=200</span><br><span class="line"></span><br><span class="line"><span class="comment"># cat apache.yml </span></span><br><span class="line">- hosts: webserver</span><br><span class="line">  remote_user: root</span><br><span class="line">  vars:</span><br><span class="line">  - package: httpd</span><br><span class="line">  - service: httpd</span><br><span class="line">  tasks:</span><br><span class="line">  - name: install httpd package</span><br><span class="line">    yum: name=&#123;&#123; package &#125;&#125; <span class="attribute">state</span>=latest</span><br><span class="line">  - name: install configuration file <span class="keyword">for</span> httpd</span><br><span class="line">    template: <span class="attribute">src</span>=/root/conf/httpd.conf <span class="attribute">dest</span>=/etc/httpd/conf/httpd.conf</span><br><span class="line">    notify: </span><br><span class="line">    - restart httpd</span><br><span class="line">  - name: start httpd service</span><br><span class="line">    service: <span class="attribute">enabled</span>=<span class="literal">true</span> name=&#123;&#123;<span class="built_in"> service </span>&#125;&#125; <span class="attribute">state</span>=started</span><br><span class="line">  </span><br><span class="line">  handlers:</span><br><span class="line">  - name: restart httpd</span><br><span class="line">    service: <span class="attribute">name</span>=httpd <span class="attribute">state</span>=restarted</span><br></pre></td></tr></table></figure>
<h2 id="七、Ansible-playbooks"><a href="#七、Ansible-playbooks" class="headerlink" title="七、Ansible playbooks"></a>七、Ansible playbooks</h2><p>playbook是由一个或多个”play”组成的列表。play的主要功能在于将事先归并为一组的主机装扮成事先通过ansible中的task定义好的角色。从根本上来讲，所有task无非是调用ansible的一个module。将多个play组织在一个playbook中，即可以让他们连同起来按事先编排的机制同唱一台大戏。下面是一个简单示例。<br><figure class="highlight pf"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">- hosts: webserver</span><br><span class="line">  vars:</span><br><span class="line">    http_port: <span class="number">80</span></span><br><span class="line">    max_clients: <span class="number">256</span></span><br><span class="line">  remote_user: root</span><br><span class="line">  tasks:</span><br><span class="line">  - name: ensure apache is at the latest version</span><br><span class="line">    yum: name=httpd <span class="keyword">state</span>=latest</span><br><span class="line">  - name: ensure apache is running</span><br><span class="line">    service: name=httpd <span class="keyword">state</span>=started</span><br><span class="line">  handlers:</span><br><span class="line">    - name: restart apache</span><br><span class="line">      service: name=httpd <span class="keyword">state</span>=restarted</span><br></pre></td></tr></table></figure></p>
<h3 id="7-1-playbook基础组件"><a href="#7-1-playbook基础组件" class="headerlink" title="7.1 playbook基础组件"></a>7.1 playbook基础组件</h3><h4 id="7-1-1-Hosts和Users"><a href="#7-1-1-Hosts和Users" class="headerlink" title="7.1.1 Hosts和Users"></a>7.1.1 Hosts和Users</h4><p>playbook中的每一个play的目的都是为了让某个或某些主机以某个指定的用户身份执行任务。hosts用于指定要执行指定任务的主机，其可以使一个或多个由冒号分隔主机组；remote_user则用于指定远程主机的执行任务的用户，如上面的实例中的<br><figure class="highlight haml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">-<span class="ruby"> <span class="symbol">hosts:</span> webserver</span></span><br><span class="line"><span class="ruby">  <span class="symbol">remote_user:</span> root</span></span><br></pre></td></tr></table></figure></p>
<p>不过，remote_user也可用于各task中，也可以通过指定其通过sudo的方式在远程主机上执行任务，其可用于play全局或其任务；此外，甚至可以在sudo时使用sudo_user指定sudo时切换的用户。<br><figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">- hosts: webserver</span><br><span class="line">  remote_user: kangvcar</span><br><span class="line">  tasks:</span><br><span class="line">   - name: test connection</span><br><span class="line">     ping:</span><br><span class="line">     remote_user: kangvcar</span><br><span class="line">     sudo: <span class="literal">yes</span></span><br></pre></td></tr></table></figure></p>
<h4 id="7-1-2-任务列表和action"><a href="#7-1-2-任务列表和action" class="headerlink" title="7.1.2 任务列表和action"></a>7.1.2 任务列表和action</h4><p>play的主题部分是task list。task list中的各任务按次序逐个在hosts中指定的所有主机上执行，即在所有主机上完成第一个任务后再开始第二个。在运行自上而下某playbook时，如果中途发生错误，所有已执行任务都可能回滚，在更正playbook后重新执行一次即可。</p>
<p>taks的目的是使用指定的参数执行模块，而在模块参数中可以使用变量。模块执行是幂等的。这意味着多次执行是安全的，因为其结果均一致。</p>
<p>每个task都应该有其name，用于playbook的执行结果输出，建议其内容尽可能清晰地描述任务执行步骤，如果为提供name，则action的结果将用于输出。</p>
<p>定义task可以使用”action: module options”或”module：options“的格式推荐使用后者以实现向后兼容。如果action一行的内容过多，也中使用在行首使用几个空白字符进行换行。<br><figure class="highlight pf"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">tasks:</span><br><span class="line">  - name:make sure apache is running</span><br><span class="line">    service: name=httpd <span class="keyword">state</span>=started</span><br></pre></td></tr></table></figure></p>
<p>在众多的模块中，只有command和shell模块仅需要给定一个列表而无需使用”key=value”格式，例如：<br><figure class="highlight dts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="symbol">tasks:</span></span><br><span class="line">  - name: disable selinux</span><br><span class="line"><span class="symbol">    command:</span> <span class="meta-keyword">/sbin/</span>setenforce <span class="number">0</span></span><br></pre></td></tr></table></figure></p>
<p>如果命令或脚本的退出码不为零，可以使用如下方式替代：<br><figure class="highlight dockerfile"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">tasks:</span><br><span class="line">  - name: <span class="keyword">run</span><span class="bash"> this <span class="built_in">command</span> and ignore the result</span></span><br><span class="line"><span class="bash">    shell: /usr/bin/somecommand || /bin/<span class="literal">true</span></span></span><br></pre></td></tr></table></figure></p>
<p>或者使用ignore_errors来忽略错误信息：<br><figure class="highlight dockerfile"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">tasks:</span><br><span class="line">  - name: <span class="keyword">run</span><span class="bash"> this <span class="built_in">command</span> and ignore the result</span></span><br><span class="line"><span class="bash">    shell: /usr/bin/somecommand</span></span><br><span class="line"><span class="bash">    ignore_errors: True</span></span><br></pre></td></tr></table></figure></p>
<h4 id="7-1-3handlers"><a href="#7-1-3handlers" class="headerlink" title="7.1.3handlers"></a>7.1.3handlers</h4><p>用于当关注的资源发生变化时采取一定的操作。</p>
<p>“notify”这个action可用于在每个play的最后被触发，这样可以避免多次有改变发生时每次都执行执行的操作，取而代之，仅在所有的变化发生完成后一次性地执行指定操作，在notify中列出的操作称为handlers，也即notify中调用handlers中定义的操作。<br><figure class="highlight haml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">-<span class="ruby"> <span class="symbol">name:</span> template configuration file</span></span><br><span class="line"><span class="ruby">  <span class="symbol">template:</span> src=template.j2 dest=<span class="regexp">/etc/foo</span>.conf</span></span><br><span class="line"><span class="ruby">  <span class="symbol">notify:</span></span></span><br><span class="line"><span class="ruby">    - restart memcached</span></span><br><span class="line"><span class="ruby">    - restart apache</span></span><br></pre></td></tr></table></figure></p>
<p>handlers是task列表，这些task与前述的task并没有本质上的不同。<br><figure class="highlight pf"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">handlers：</span><br><span class="line">  - name: restart memcached</span><br><span class="line">    service: name=memcached <span class="keyword">state</span>=restarted</span><br><span class="line">  - name: restart apache</span><br><span class="line">    service: name=apache <span class="keyword">state</span>=restarted</span><br></pre></td></tr></table></figure></p>
<h4 id="简单示例1："><a href="#简单示例1：" class="headerlink" title="简单示例1："></a>简单示例1：</h4><figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># cat nginx.yml </span></span><br><span class="line">- hosts: webserver</span><br><span class="line">  remote_user: root</span><br><span class="line">  tasks:</span><br><span class="line">  - name: create nginxn group</span><br><span class="line">    group: <span class="attribute">name</span>=nginx <span class="attribute">system</span>=<span class="literal">yes</span> <span class="attribute">gid</span>=208</span><br><span class="line">  - name: create nginx user</span><br><span class="line">    user: <span class="attribute">name</span>=nginx <span class="attribute">uid</span>=208 <span class="attribute">group</span>=nginx <span class="attribute">system</span>=<span class="literal">yes</span></span><br><span class="line"></span><br><span class="line">- hosts: dbserver</span><br><span class="line">  remote_user: root</span><br><span class="line">  tasks:</span><br><span class="line">  - name: copy file <span class="keyword">to</span> dbserver</span><br><span class="line">    copy: <span class="attribute">src</span>=/etc/inittab <span class="attribute">dest</span>=/tmp/inittab.ans</span><br><span class="line">    </span><br><span class="line"><span class="comment"># ansible-playbook nginx.yml</span></span><br></pre></td></tr></table></figure>
<h4 id="简单示例2："><a href="#简单示例2：" class="headerlink" title="简单示例2："></a>简单示例2：</h4><figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># cat apache.yml </span></span><br><span class="line">- hosts: webserver</span><br><span class="line">  remote_user: root</span><br><span class="line">  tasks:</span><br><span class="line">  - name: install httpd package</span><br><span class="line">    yum: <span class="attribute">name</span>=httpd <span class="attribute">state</span>=latest</span><br><span class="line">  - name: install configuration file <span class="keyword">for</span> httpd</span><br><span class="line">    copy: <span class="attribute">src</span>=/root/conf/httpd.conf <span class="attribute">dest</span>=/etc/httpd/conf/httpd.conf</span><br><span class="line">  - name: start httpd service</span><br><span class="line">    service: <span class="attribute">enabled</span>=<span class="literal">true</span> <span class="attribute">name</span>=httpd <span class="attribute">state</span>=started</span><br><span class="line"></span><br><span class="line"><span class="comment"># ansible-playbook apache.yml</span></span><br></pre></td></tr></table></figure>
<h4 id="handlers-示例："><a href="#handlers-示例：" class="headerlink" title="handlers 示例："></a>handlers 示例：</h4><figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># cat apache.yml </span></span><br><span class="line">- hosts: webserver</span><br><span class="line">  remote_user: root</span><br><span class="line">  tasks:</span><br><span class="line">  - name: install httpd package</span><br><span class="line">    yum: <span class="attribute">name</span>=httpd <span class="attribute">state</span>=latest</span><br><span class="line">  - name: install configuration file <span class="keyword">for</span> httpd</span><br><span class="line">    copy: <span class="attribute">src</span>=/root/conf/httpd.conf <span class="attribute">dest</span>=/etc/httpd/conf/httpd.conf</span><br><span class="line">    notify: </span><br><span class="line">    - restart httpd</span><br><span class="line">  - name: start httpd service</span><br><span class="line">    service: <span class="attribute">enabled</span>=<span class="literal">true</span> <span class="attribute">name</span>=httpd <span class="attribute">state</span>=started</span><br><span class="line">  </span><br><span class="line">  handlers:</span><br><span class="line">  - name: restart httpd</span><br><span class="line">    service: <span class="attribute">name</span>=httpd <span class="attribute">state</span>=restarted</span><br><span class="line"></span><br><span class="line"><span class="comment">#  ansible-playbook apache.yml</span></span><br></pre></td></tr></table></figure>
<h4 id="variable-示例1："><a href="#variable-示例1：" class="headerlink" title="variable 示例1："></a>variable 示例1：</h4><figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># cat apache.yml </span></span><br><span class="line">- hosts: webserver</span><br><span class="line">  remote_user: root</span><br><span class="line">  vars:</span><br><span class="line">  - package: httpd</span><br><span class="line">  - service: httpd</span><br><span class="line">  tasks:</span><br><span class="line">  - name: install httpd package</span><br><span class="line">    yum: name=&#123;&#123; package &#125;&#125; <span class="attribute">state</span>=latest</span><br><span class="line">  - name: install configuration file <span class="keyword">for</span> httpd</span><br><span class="line">    copy: <span class="attribute">src</span>=/root/conf/httpd.conf <span class="attribute">dest</span>=/etc/httpd/conf/httpd.conf</span><br><span class="line">    notify: </span><br><span class="line">    - restart httpd</span><br><span class="line">  - name: start httpd service</span><br><span class="line">    service: <span class="attribute">enabled</span>=<span class="literal">true</span> name=&#123;&#123;<span class="built_in"> service </span>&#125;&#125; <span class="attribute">state</span>=started</span><br><span class="line">  </span><br><span class="line">  handlers:</span><br><span class="line">  - name: restart httpd</span><br><span class="line">    service: <span class="attribute">name</span>=httpd <span class="attribute">state</span>=restarted</span><br></pre></td></tr></table></figure>
<h4 id="variable-示例2：-在playbook中可以使用所有的变量"><a href="#variable-示例2：-在playbook中可以使用所有的变量" class="headerlink" title="variable 示例2：(在playbook中可以使用所有的变量)"></a>variable 示例2：(在playbook中可以使用所有的变量)</h4><figure class="highlight dockerfile"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># cat facts.yml </span></span><br><span class="line">- hosts: webserver</span><br><span class="line">  remote_user: root</span><br><span class="line">  tasks:</span><br><span class="line">  - name: <span class="keyword">copy</span><span class="bash"> file</span></span><br><span class="line"><span class="bash">    copy: content=<span class="string">"&#123;&#123; ansible_all_ipv4_addresses &#125;&#125; "</span> dest=/tmp/vars.ans</span></span><br></pre></td></tr></table></figure>
<h2 id="八、roles"><a href="#八、roles" class="headerlink" title="八、roles"></a>八、roles</h2><p>ansible自1.2版本引入的新特性，用于层次性、结构化地组织playbook。roles能够根据层次型结构自动转载变量文件、tasks以及handlers等。要使用roles只需要在playbook中使用include指令即可。简单来讲，roles就是通过分别将变量、文件、任务、模板以及处理器放置于单独的目录中，并可以便捷地include他们的一种机制。角色一般用于基于主机构建服务的场景中，但也可以使用于构建守护进程的场景中。<br>role是使ansible的状态管理可复用很重要的一个概念，很多时候你只需要在自己的playbook里引用下别人的role即可，大家写的role可以相互共享，相互参考。官方也提供了ansible-galaxy这个命令用于安装社区分享的role，具体可参考<a href="https://galaxy.ansible.com/explore#/" target="_blank" rel="external">Galaxy官网</a></p>
<p>一个roles的案例如下所示：<br><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">site.yml</span><br><span class="line">webserver.yml</span><br><span class="line">fooserver.yml</span><br><span class="line">roles/</span><br><span class="line">    common/</span><br><span class="line">        files/</span><br><span class="line">        templates/</span><br><span class="line">        tasks/</span><br><span class="line">        handlers/</span><br><span class="line">        vars/</span><br><span class="line">        meta/</span><br><span class="line">    webserver/</span><br><span class="line">        files/</span><br><span class="line">        templates/</span><br><span class="line">        tasks/</span><br><span class="line">        handlers/</span><br><span class="line">        vars/</span><br><span class="line">        meta/</span><br></pre></td></tr></table></figure></p>
<p>而在playbook中，可以这样使用roles<br><figure class="highlight haml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">-<span class="ruby"> <span class="symbol">hosts:</span> webserver</span></span><br><span class="line"><span class="ruby">  <span class="symbol">roles:</span></span></span><br><span class="line"><span class="ruby">    - common  </span></span><br><span class="line"><span class="ruby">    - webserver</span></span><br></pre></td></tr></table></figure></p>
<p>也可以向roles传递参数，例如：<br><figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">-</span> <span class="selector-tag">hosts</span>: <span class="selector-tag">webserver</span></span><br><span class="line">  <span class="selector-tag">roles</span>:</span><br><span class="line">    <span class="selector-tag">-</span> <span class="selector-tag">common</span></span><br><span class="line">    <span class="selector-tag">-</span> &#123; <span class="attribute">role</span>: foo_app_instance, dir:<span class="string">'/opt/a'</span>,port:<span class="number">5000</span>&#125;</span><br><span class="line">    <span class="selector-tag">-</span> &#123; <span class="attribute">role</span>: foo_app_instance, dir:<span class="string">'/opt/b'</span>,port:<span class="number">5001</span>&#125;</span><br></pre></td></tr></table></figure></p>
<p>甚至也可以条件式地使用roles，例如：<br><figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">-</span> <span class="selector-tag">hosts</span>：<span class="selector-tag">webserver</span></span><br><span class="line">  <span class="selector-tag">roles</span>:</span><br><span class="line">    <span class="selector-tag">-</span> &#123; <span class="attribute">role</span>: some_role, when: <span class="string">"ansible_so_family == 'RedHat"</span> &#125;</span><br></pre></td></tr></table></figure></p>
<h3 id="8-1-创建role的步骤"><a href="#8-1-创建role的步骤" class="headerlink" title="8.1 创建role的步骤"></a>8.1 创建role的步骤</h3><ol>
<li>创建以roles命名的目录：</li>
<li>在roles目录中分别创建以各角色命名的目录，如webserver等</li>
<li>在每个角色命名的目录中分别创建files、handlers、meta、tasks、templates和vars目录；用不到的目录可以创建为空目录，也可以不创建</li>
<li>在playbook文件中，调用各角色</li>
</ol>
<h3 id="8-2-role内各目录中可应用的文件"><a href="#8-2-role内各目录中可应用的文件" class="headerlink" title="8.2 role内各目录中可应用的文件"></a>8.2 role内各目录中可应用的文件</h3><ul>
<li>task目录：至少应该包含一个为main.yml的文件，其定义了此角色的任务列表；此文件可以使用include包含其它的位于此目录中的task文件；</li>
<li>file目录：存放由copy或script等模板块调用的文件；</li>
<li>template目录：template模块会自动在此目录中寻找jinja2模板文件；</li>
<li>handlers目录：此目录中应当包含一个main.yml文件，用于定义此角色用到的各handlers，在handler中使用inclnude包含的其它的handlers文件也应该位于此目录中；</li>
<li>vars目录：应当包含一个main.yml文件，用于定义此角色用到的变量</li>
<li>meta目录：应当包含一个main.yml文件，用于定义此角色的特殊设定及其依赖关系；ansible1.3及其以后的版本才支持；</li>
<li>default目录：应当包含一个main.yml文件,用于为当前角色设定默认变量时使用此目录；<figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># mkdir -pv ansible_playbooks/roles/&#123;webserver,dbserver&#125;/&#123;tasks,files,templates,meta,handlers,vars&#125; </span></span><br><span class="line"><span class="comment"># cp /etc/httpd/conf/httpd.conf files/  </span></span><br><span class="line"><span class="comment"># pwd</span></span><br><span class="line">/root/ansible_playbooks/roles/webserver </span><br><span class="line"><span class="comment"># cat tasks/main.yml </span></span><br><span class="line">- name: install httpd package</span><br><span class="line">  yum: <span class="attribute">name</span>=httpd <span class="attribute">state</span>=present</span><br><span class="line">- name: install configuretion file</span><br><span class="line">  copy: <span class="attribute">src</span>=httpd.conf <span class="attribute">dest</span>=/etc/httpd/conf/httpd.conf</span><br><span class="line">  tags:</span><br><span class="line">  - conf</span><br><span class="line">  notify:</span><br><span class="line">  - restart httpd</span><br><span class="line">- name: start httpd</span><br><span class="line">  service: <span class="attribute">name</span>=httpd <span class="attribute">state</span>=started</span><br><span class="line"></span><br><span class="line"><span class="comment"># cat handlers/main.yml </span></span><br><span class="line">- name: restart httpd</span><br><span class="line">  service: <span class="attribute">name</span>=httpd <span class="attribute">state</span>=restarted</span><br><span class="line">    </span><br><span class="line"><span class="comment"># pwd;ls</span></span><br><span class="line">/root/ansible_playbooks</span><br><span class="line">roles  site.yml </span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># cat site.yml </span></span><br><span class="line">- hosts: webserver</span><br><span class="line">  remote_user: root</span><br><span class="line">  roles:</span><br><span class="line">  - webserver</span><br><span class="line"></span><br><span class="line"><span class="comment"># ansible-playbook site.yml</span></span><br></pre></td></tr></table></figure>
</li>
</ul>
<h2 id="九、Tags"><a href="#九、Tags" class="headerlink" title="九、Tags"></a>九、Tags</h2><p>tags用于让用户选择运行或跳过playbook中的部分代码。ansible具有幂等性，因此会自动跳过没有变化的部分，即便如此，有些代码为测试其确实没有发生变化的时间依然会非常的长。此时，如果确信其没有变化，就可以通过tags跳过此些代码片段。</p>
<p>tags：在playbook可以为某个或某些任务定义一个”标签”，在执行此playbook时，通过为ansible-playbook命令使用–tags选项能耐实现仅运行指定的tasks而非所有的；<br><figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># cat apache.yml </span></span><br><span class="line">- hosts: webserver</span><br><span class="line">  remote_user: root</span><br><span class="line">  vars:</span><br><span class="line">  - package: httpd</span><br><span class="line">  - service: httpd</span><br><span class="line">  tasks:</span><br><span class="line">  - name: install httpd package</span><br><span class="line">    yum: name=&#123;&#123; package &#125;&#125; <span class="attribute">state</span>=latest</span><br><span class="line">  - name: install configuration file <span class="keyword">for</span> httpd</span><br><span class="line">    template: <span class="attribute">src</span>=/root/conf/httpd.conf <span class="attribute">dest</span>=/etc/httpd/conf/httpd.conf</span><br><span class="line">    tags:</span><br><span class="line">    - conf</span><br><span class="line">    notify: </span><br><span class="line">    - restart httpd</span><br><span class="line">  - name: start httpd service</span><br><span class="line">    service: <span class="attribute">enabled</span>=<span class="literal">true</span> name=&#123;&#123;<span class="built_in"> service </span>&#125;&#125; <span class="attribute">state</span>=started</span><br><span class="line">  </span><br><span class="line">  handlers:</span><br><span class="line">  - name: restart httpd</span><br><span class="line">    service: <span class="attribute">name</span>=httpd <span class="attribute">state</span>=restarted</span><br><span class="line"></span><br><span class="line"><span class="comment"># ansible-playbook apache.yml --tags='conf'</span></span><br></pre></td></tr></table></figure></p>
<p>特殊tags：always   #无论如何都会运行</p>
<p>我的博客即将搬运同步至腾讯云+社区，邀请大家一同入驻：<a href="https://cloud.tencent.com/developer/support-plan?invite_code=1py02fdsoyp0l" target="_blank" rel="external">https://cloud.tencent.com/developer/support-plan?invite_code=1py02fdsoyp0l</a></p>

      
    </div>
    
    
    


  


    

    
      <div>
        <div align="center">
 
   <div class="">
   <p>&nbsp</p>
   <p>&nbsp</p>
   <p><span>
   <b>本文地址：</b><a href="/Ansible极简教程/" title="Ansible极简教程">http://www.kangvcar.com/Ansible极简教程/</a><br/><b>转载请注明出处，谢谢！</b>
   </span></p>
   </div>
 
</div>


<div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，随意打赏！您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.jpg" alt="Kangvcar 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="Kangvcar 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <div>
      
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------感谢您的阅读-------------</div>
    
</div>
      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Ansible/" rel="tag"><i class="fa fa-tag"></i> Ansible</a>
          
            <a href="/tags/极简教程系列/" rel="tag"><i class="fa fa-tag"></i> 极简教程系列</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/手把手教你用1行Python代码实现FTP服务器-Pyftpdlib/" rel="next" title="手把手教你用1行Python代码实现FTP服务器 -- Pyftpdlib">
                <i class="fa fa-chevron-left"></i> 手把手教你用1行Python代码实现FTP服务器 -- Pyftpdlib
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/Cobbler-快速入门指南/" rel="prev" title="Cobbler 快速入门指南">
                Cobbler 快速入门指南 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
<span class="jiathis_txt">分享到：</span>
<a class="jiathis_button_fav">收藏夹</a>
<a class="jiathis_button_copy">复制网址</a>
<a class="jiathis_button_email">邮件</a>
<a class="jiathis_button_weixin">微信</a>
<a class="jiathis_button_qzone">QQ空间</a>
<a class="jiathis_button_tqq">腾讯微博</a>
<a class="jiathis_button_douban">豆瓣</a>
<a class="jiathis_button_share">一键分享</a>

<a href="http://www.jiathis.com/share?uid=2140465" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank">更多</a>
<a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript" >
var jiathis_config={
  data_track_clickback:true,
  summary:"",
  shortUrl:false,
  hideMore:false
}
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js?uid=" charset="utf-8"></script>
<!-- JiaThis Button END -->
      
    </div>
  </div>


          </div>
          


          

  
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zMTgzNi84NDAw"></div>


  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/uploads/avatar.png"
                alt="Kangvcar" />
            
              <p class="site-author-name" itemprop="name">Kangvcar</p>
              <p class="site-description motion-element" itemprop="description">知识的广度是深度的副产品</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">28</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">13</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">32</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          <div class="links-of-author motion-element">
            
              
                <span class="links-of-author-item">
                  <a href="https://github.com/kangvcar" target="_blank" title="GitHub">
                    
                      <i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="http://cv.kangvcar.com" target="_blank" title="我的简历">
                    
                      <i class="fa fa-fw fa-user"></i>我的简历</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://twitter.com/kangvcar" target="_blank" title="Twitter">
                    
                      <i class="fa fa-fw fa-twitter"></i>Twitter</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="http://www.jianshu.com/u/d9c480744afd" target="_blank" title="简书">
                    
                      <i class="fa fa-fw fa-globe"></i>简书</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="http://blog.csdn.net/kangvcar" target="_blank" title="CSDN">
                    
                      <i class="fa fa-fw fa-globe"></i>CSDN</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://my.oschina.net/kangvcar/blog" target="_blank" title="OSChina">
                    
                      <i class="fa fa-fw fa-globe"></i>OSChina</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:kangvcar@126.com" target="_blank" title="E-Mail">
                    
                      <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                </span>
              
            
          </div>

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Ansible-极简教程"><span class="nav-number">1.</span> <span class="nav-text">Ansible 极简教程</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#一、基本部署"><span class="nav-number">1.1.</span> <span class="nav-text">一、基本部署</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#简介"><span class="nav-number">1.1.1.</span> <span class="nav-text">简介</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#特性"><span class="nav-number">1.1.2.</span> <span class="nav-text">特性</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#安装Ansible"><span class="nav-number">1.1.3.</span> <span class="nav-text">安装Ansible</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Ansible配置文件"><span class="nav-number">1.1.4.</span> <span class="nav-text">Ansible配置文件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用秘钥方式连接"><span class="nav-number">1.1.5.</span> <span class="nav-text">使用秘钥方式连接</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用帮助"><span class="nav-number">1.1.6.</span> <span class="nav-text">使用帮助</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Ansible命令应用基础"><span class="nav-number">1.1.7.</span> <span class="nav-text">Ansible命令应用基础</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#二、常见模块"><span class="nav-number">1.2.</span> <span class="nav-text">二、常见模块</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#command"><span class="nav-number">1.2.1.</span> <span class="nav-text">command</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#cron"><span class="nav-number">1.2.2.</span> <span class="nav-text">cron</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#user"><span class="nav-number">1.2.3.</span> <span class="nav-text">user</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#group"><span class="nav-number">1.2.4.</span> <span class="nav-text">group</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#file"><span class="nav-number">1.2.5.</span> <span class="nav-text">file</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#ping"><span class="nav-number">1.2.6.</span> <span class="nav-text">ping</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#service"><span class="nav-number">1.2.7.</span> <span class="nav-text">service</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#shell"><span class="nav-number">1.2.8.</span> <span class="nav-text">shell</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#script"><span class="nav-number">1.2.9.</span> <span class="nav-text">script</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#yum"><span class="nav-number">1.2.10.</span> <span class="nav-text">yum</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#setup"><span class="nav-number">1.2.11.</span> <span class="nav-text">setup</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#三、Ansible-playbook"><span class="nav-number">1.3.</span> <span class="nav-text">三、Ansible playbook</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#四、YAML"><span class="nav-number">1.4.</span> <span class="nav-text">四、YAML</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#4-1-YAML介绍"><span class="nav-number">1.4.1.</span> <span class="nav-text">4.1 YAML介绍</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-2-YAML语法"><span class="nav-number">1.4.2.</span> <span class="nav-text">4.2 YAML语法</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#五、Ansible基础元素"><span class="nav-number">1.5.</span> <span class="nav-text">五、Ansible基础元素</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#5-1-变量"><span class="nav-number">1.5.1.</span> <span class="nav-text">5.1 变量</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#5-1-1-变量命名"><span class="nav-number">1.5.1.1.</span> <span class="nav-text">5.1.1 变量命名</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5-1-2-facts"><span class="nav-number">1.5.1.2.</span> <span class="nav-text">5.1.2 facts</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5-1-3-register"><span class="nav-number">1.5.1.3.</span> <span class="nav-text">5.1.3 register</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5-1-4-通过命令行传递变量"><span class="nav-number">1.5.1.4.</span> <span class="nav-text">5.1.4 通过命令行传递变量</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5-1-5-通过roles传递变量"><span class="nav-number">1.5.1.5.</span> <span class="nav-text">5.1.5 通过roles传递变量</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-2-Inventory"><span class="nav-number">1.5.2.</span> <span class="nav-text">5.2 Inventory</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#5-2-1-inventory文件格式"><span class="nav-number">1.5.2.1.</span> <span class="nav-text">5.2.1 inventory文件格式</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5-2-2-主机变量"><span class="nav-number">1.5.2.2.</span> <span class="nav-text">5.2.2 主机变量</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5-2-3-组变量"><span class="nav-number">1.5.2.3.</span> <span class="nav-text">5.2.3 组变量</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5-2-4-组嵌套"><span class="nav-number">1.5.2.4.</span> <span class="nav-text">5.2.4 组嵌套</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5-2-5-inventory参数"><span class="nav-number">1.5.2.5.</span> <span class="nav-text">5.2.5 inventory参数</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-3-条件测试"><span class="nav-number">1.5.3.</span> <span class="nav-text">5.3 条件测试</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#5-3-1-when语句"><span class="nav-number">1.5.3.1.</span> <span class="nav-text">5.3.1 when语句</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-4-迭代"><span class="nav-number">1.5.4.</span> <span class="nav-text">5.4 迭代</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#六、模板示例："><span class="nav-number">1.6.</span> <span class="nav-text">六、模板示例：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#七、Ansible-playbooks"><span class="nav-number">1.7.</span> <span class="nav-text">七、Ansible playbooks</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#7-1-playbook基础组件"><span class="nav-number">1.7.1.</span> <span class="nav-text">7.1 playbook基础组件</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#7-1-1-Hosts和Users"><span class="nav-number">1.7.1.1.</span> <span class="nav-text">7.1.1 Hosts和Users</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#7-1-2-任务列表和action"><span class="nav-number">1.7.1.2.</span> <span class="nav-text">7.1.2 任务列表和action</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#7-1-3handlers"><span class="nav-number">1.7.1.3.</span> <span class="nav-text">7.1.3handlers</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#简单示例1："><span class="nav-number">1.7.1.4.</span> <span class="nav-text">简单示例1：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#简单示例2："><span class="nav-number">1.7.1.5.</span> <span class="nav-text">简单示例2：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#handlers-示例："><span class="nav-number">1.7.1.6.</span> <span class="nav-text">handlers 示例：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#variable-示例1："><span class="nav-number">1.7.1.7.</span> <span class="nav-text">variable 示例1：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#variable-示例2：-在playbook中可以使用所有的变量"><span class="nav-number">1.7.1.8.</span> <span class="nav-text">variable 示例2：(在playbook中可以使用所有的变量)</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#八、roles"><span class="nav-number">1.8.</span> <span class="nav-text">八、roles</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#8-1-创建role的步骤"><span class="nav-number">1.8.1.</span> <span class="nav-text">8.1 创建role的步骤</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#8-2-role内各目录中可应用的文件"><span class="nav-number">1.8.2.</span> <span class="nav-text">8.2 role内各目录中可应用的文件</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#九、Tags"><span class="nav-number">1.9.</span> <span class="nav-text">九、Tags</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

<div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Kangvcar</span>

  
</div>


<div class="powered-by">
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_pv">
    本站访客数:<span id="busuanzi_value_site_pv"></span>次
</span>
</div>








  <span class="post-meta-divider">|</span>




<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共32.7k字</span>
</div>
        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.3"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>



  


  

    
      <script id="dsq-count-scr" src="https://kangvcar.disqus.com/count.js" async></script>
    

    
      <script type="text/javascript">
        var disqus_config = function () {
          this.page.url = 'http://www.kangvcar.com/Ansible极简教程/';
          this.page.identifier = 'Ansible极简教程/';
          this.page.title = 'Ansible极简教程';
        };
        var d = document, s = d.createElement('script');
        s.src = 'https://kangvcar.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      </script>
    

  




	





  












<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="//unpkg.com/valine/dist/Valine.min.js"></script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  



  
    <script type="text/javascript" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script>
  
  
<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/love.js"></script>

</body>
</html>
